package com.hmdp.utils;

import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.hmdp.dto.Result;
import com.hmdp.entity.Shop;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;

import static com.hmdp.utils.RedisConstants.*;

@Slf4j
@Component
public class CacheClient {
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    //适用于解决缓存穿透的set
    public void set(String key, Object value, Long time, TimeUnit timeUnit){
        stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(value), time, timeUnit);
    }
    //适用于解决缓存击穿的set（热点问题）
    public void setWithLogicExpire(String key, Object value, Long time, TimeUnit timeUnit){
        RedisData redisData=new RedisData();
        redisData.setData(value);
        redisData.setExpireTime(LocalDateTime.now().plusSeconds(timeUnit.toSeconds(time)));
        stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(redisData));
    }
    //适用于解决缓存穿透的query
    public <R,ID> R queryWithPassThrough(
            String keyPrefix, ID id, Class<R> type, Function<ID,R> dbFallBack,Long time, TimeUnit timeUnit){
        String key = keyPrefix + id;
        String json = stringRedisTemplate.opsForValue().get(key);
        if(StrUtil.isNotBlank(json)){
            return JSONUtil.toBean(json, type);
        }
        //解决缓存穿透
        if(json!=null){
            return null;
        }
        //查询数据库
        R r = dbFallBack.apply(id);
        if(r == null){
            stringRedisTemplate.opsForValue().set(key,"",CACHE_NULL_TTL,TimeUnit.MINUTES);
            return null;
        }
        this.set(key,r,time,timeUnit);
        return r;
    }
    private static final ExecutorService CACHE_BUILD_EXECUTOR= Executors.newFixedThreadPool(10);
    //适用于解决缓存击穿的query（热点问题）
    public <R,ID> R queryWithLogicalExpire(
            String keyPrefix,String lockPrefix,ID id,Class<R> type,Function<ID,R> dbFallBack,Long time,TimeUnit timeUnit){
        String key=keyPrefix + id;
        String lockKey=lockPrefix +id;
        String redisDataJson = stringRedisTemplate.opsForValue().get(key);
        if(StrUtil.isBlank(redisDataJson)){
            return null;
        }
        RedisData redisData = JSONUtil.toBean(redisDataJson, RedisData.class);
        LocalDateTime expire = redisData.getExpireTime();
        R r= JSONUtil.toBean((JSONObject) redisData.getData(),type);
        if(expire.isAfter(LocalDateTime.now())){
            return r;
        }
        //获取互斥锁
        boolean success = getLock(lockKey);
        if(success) {
            //获得锁后再次检测redis，做双重检测
            redisDataJson=stringRedisTemplate.opsForValue().get(key);
            if(StrUtil.isBlank(redisDataJson)){
                return null;
            }
            redisData=JSONUtil.toBean(redisDataJson, RedisData.class);
            expire = redisData.getExpireTime();
            r= JSONUtil.toBean((JSONObject) redisData.getData(),type);
            if(expire.isAfter(LocalDateTime.now())){
                return r;
            }
            //开启独立线程进行缓存重建
            CACHE_BUILD_EXECUTOR.submit(()->{
                try {
                    R apply = dbFallBack.apply(id);
                    this.setWithLogicExpire(key,apply,time,timeUnit);
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }finally {
                    //释放锁
                    unLock(lockKey);
                }
            });
        }
        //返回过期店铺信息
        return r;
    }
    private boolean getLock(String key){
        Boolean b = stringRedisTemplate.opsForValue().setIfAbsent(key, "1", 10, TimeUnit.SECONDS);
        return BooleanUtil.isTrue(b);
    }

    private void unLock(String key){
        stringRedisTemplate.delete(key);
    }
}
